package pro.shushi.pamirs.demo.core.service;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import pro.shushi.pamirs.core.common.standard.service.impl.AbstractStandardModelService;
import pro.shushi.pamirs.demo.api.enumeration.OrderStatusEnum;
import pro.shushi.pamirs.demo.api.model.*;
import pro.shushi.pamirs.demo.api.service.OrderService;
import pro.shushi.pamirs.meta.annotation.Fun;

import java.math.BigDecimal;
import java.util.List;

@Service
@Fun(OrderService.FUN_NAMESPACE)
public class OrderServiceImpl extends AbstractStandardModelService<Order> implements OrderService {


    @Override
    public Order create(Order data) {
        List<OrderDetail> orderDetails = data.getOrderDetails();
        BigDecimal totalPublicAmount = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderDetail orderDetail : orderDetails) {
            // TODO:改成批量查询提供性能
            ProductStock productStock = new ProductStock().queryById(orderDetail.getProductStock().getId());
            ProductPrice productPrice = new ProductPrice().queryById(orderDetail.getProductPrice().getId());
            BigDecimal publicPrice = productPrice.getPublicPrice();
            BigDecimal price = productPrice.getPrice();

            orderDetail.setAccountPrice(price);
            orderDetail.setPublicPrice(publicPrice);

            BigDecimal amount = price.multiply(BigDecimal.valueOf(orderDetail.getNum()));
            BigDecimal publicAmount = publicPrice.multiply(BigDecimal.valueOf(orderDetail.getNum()));
            totalPublicAmount = totalPublicAmount.add(publicAmount);
            totalAmount = totalAmount.add(amount);
            orderDetail.setAmount(amount);
            orderDetail.setPublicAmount(publicAmount);

            int last = productStock.getLast() - orderDetail.getNum();
            productStock.setLast(last);
            productStock.updateById();
        }

        data.setAmount(totalAmount);
        data.setPublicAmount(totalPublicAmount);
        data.setStatus(OrderStatusEnum.un_confirm);
        data.create();

        data.fieldSave(Order::getOrderDetails);
        for (OrderDetail orderDetail : orderDetails) {
            List<OrderPassenger> orderPassengers = orderDetail.getOrderPassengers();
            if (CollectionUtils.isNotEmpty(orderPassengers)) {
                orderPassengers.forEach(passenger -> {
                    passenger.setOrderDetailId(orderDetail.getId());
                });
            }
            orderDetail.fieldSave(OrderDetail::getOrderPassengers);
        }

        List<OrderContacts> orderContacts = data.getOrderContacts();
        if (CollectionUtils.isNotEmpty(orderContacts)) {
            orderContacts.forEach(contact -> {
                contact.setOrderId(data.getId());
            });
        }
        data.fieldSave(Order::getOrderContacts);

        return data;
    }
}
